package sfmc.biz.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import sfmc.biz.service.SfmcCustomerService;
import sfmc.biz.vo.Sfmc_TB_CUSTOMER;
import sfmc.common.util.DateUtil;

@Controller
public class SfmcCustomerController {
	
	protected Log log = LogFactory.getLog(this.getClass());
	
	@Autowired 
	private SfmcCustomerService sfmcCustomerService;
	
	@RequestMapping(value ="/customer_list.do")
	public ModelAndView list(ModelAndView mv, HttpSession session, HttpServletRequest request, Sfmc_TB_CUSTOMER sfmc_TB_CUSTOMER){

		mv.setViewName("/customer/customer_list");
		
		List<Sfmc_TB_CUSTOMER> customerList = sfmcCustomerService.getCustomerList(sfmc_TB_CUSTOMER);
		
		GsonBuilder gsonbuilder = new GsonBuilder();
		Gson gson = gsonbuilder.create();
		gson = gsonbuilder.setPrettyPrinting().create();
		
		mv.addObject("customerlist", gson.toJson(customerList));
		mv.addObject("customerdata", sfmc_TB_CUSTOMER);
		
		return mv;
	}
	
	@RequestMapping(value ="/customer_save.do" , method = RequestMethod.POST)
	public ModelAndView save(ModelAndView mv, HttpSession session, HttpServletRequest request, Sfmc_TB_CUSTOMER sfmc_TB_CUSTOMER){
		
		mv.setViewName("/customer/customer_result");

		int returnVal = -1;
		String type = "";
		
		if(sfmc_TB_CUSTOMER.getDataCustIdx() == 0){
			returnVal = sfmcCustomerService.insertCustomer(sfmc_TB_CUSTOMER);
			type = "C";
		}else{
			returnVal = sfmcCustomerService.updateCustomer(sfmc_TB_CUSTOMER);
			type = "U";
		}
		
		mv.addObject("customerdata", sfmc_TB_CUSTOMER);
		mv.addObject("returnVal", returnVal);
		mv.addObject("type", type);
		return mv;
	}
	
	@RequestMapping(value ="/customer_delete.do" , method = RequestMethod.POST)
	public ModelAndView delete(ModelAndView mv, HttpSession session, HttpServletRequest request, Sfmc_TB_CUSTOMER sfmc_TB_CUSTOMER){
		
		mv.setViewName("/customer/customer_result");

		int returnVal = -1;
		String type = "D";
		
		if(sfmc_TB_CUSTOMER.getDataCustIdx() != 0){
			returnVal = sfmcCustomerService.deleteCustomer(sfmc_TB_CUSTOMER);
		}
		
		mv.addObject("customerdata", sfmc_TB_CUSTOMER);
		mv.addObject("returnVal", returnVal);
		mv.addObject("type", type);		
		return mv;
	}
}
